#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 2222
#define BUFFSIZE 4096
#define ERR_EXIT(m) (perror(m), exit(EXIT_FAILURE))

int conn_server(const char *server_ip, int server_port)
{
	int connfd;
	struct sockaddr_in saddr;

	if((connfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		ERR_EXIT("socket");
	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(SERVER_PORT);
	if(inet_pton(AF_INET, server_ip, &saddr.sin_addr) <= 0)
		ERR_EXIT("inet_pton");
	if(connect(connfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
		ERR_EXIT("connect");
	return connfd;
}

void get_str(char *str, size_t size)
{
	char *p;

	fgets(str, size, stdin);
	if((p = strchr(str, '\n')))
		*p = '\0';
}

int main()
{
	int connfd, ret;
	char buf[BUFFSIZE];

	connfd = conn_server(SERVER_IP, SERVER_PORT);
	printf("Please input the expression to calculate. Input \"quit\" to quit program!\n\n");
	for( ; ; ) {
		get_str(buf, sizeof(buf));
		if(write(connfd, buf, strlen(buf)) < 0)
			ERR_EXIT("write");
		if(!strcmp("quit", buf))
			break;
		if((ret = read(connfd, buf, sizeof(buf))) < 0)
			ERR_EXIT("read");
		buf[ret] = '\0';
		printf("%s\n\n", buf);
	}
	close(connfd);
	return 0;
}
